package com.ruoyi.merchant.service.impl;

import com.alibaba.fastjson2.JSON;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.merchant.domain.OrderReview;
import com.ruoyi.merchant.domain.vo.ReplyReviewRequest;
import com.ruoyi.merchant.domain.vo.ReviewStatisticsVO;
import com.ruoyi.merchant.mapper.OrderReviewMapper;
import com.ruoyi.merchant.service.IOrderReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 订单评价Service业务层处理
 */
@Service
public class OrderReviewServiceImpl implements IOrderReviewService {

    @Autowired
    private OrderReviewMapper orderReviewMapper;

    /**
     * 查询商家评价列表
     *
     * @param orderReview 订单评价
     * @return 订单评价
     */
    @Override
    public List<OrderReview> selectMerchantReviewList(OrderReview orderReview) {
        List<OrderReview> list = orderReviewMapper.selectMerchantReviewList(orderReview);
        
        // 处理图片JSON数组
        list.forEach(review -> {
            if (StringUtils.isNotEmpty(review.getImages())) {
                try {
                    review.setImageList(JSON.parseArray(review.getImages(), String.class));
                } catch (Exception e) {
                    review.setImageList(null);
                }
            }
            // 设置是否已回复标识
            review.setReplied(StringUtils.isNotEmpty(review.getReplyContent()));
        });
        
        return list;
    }

    /**
     * 查询订单评价详情
     *
     * @param reviewId 评价ID
     * @return 订单评价
     */
    @Override
    public OrderReview selectReviewById(Long reviewId) {
        OrderReview review = orderReviewMapper.selectReviewById(reviewId);
        if (review != null && StringUtils.isNotEmpty(review.getImages())) {
            try {
                review.setImageList(JSON.parseArray(review.getImages(), String.class));
            } catch (Exception e) {
                review.setImageList(null);
            }
            review.setReplied(StringUtils.isNotEmpty(review.getReplyContent()));
        }
        return review;
    }

    /**
     * 商家回复评价
     *
     * @param request 回复请求
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int replyReview(ReplyReviewRequest request) {
        // 查询评价是否存在
        OrderReview review = orderReviewMapper.selectReviewById(request.getReviewId());
        if (review == null) {
            throw new ServiceException("评价不存在");
        }
        
        // 检查是否已回复
        if (StringUtils.isNotEmpty(review.getReplyContent())) {
            throw new ServiceException("该评价已回复，不可重复回复");
        }
        
        // 更新回复
        OrderReview updateReview = new OrderReview();
        updateReview.setReviewId(request.getReviewId());
        updateReview.setReplyContent(request.getReplyContent());
        
        return orderReviewMapper.updateReviewReply(updateReview);
    }

    /**
     * 查询商家评价统计
     *
     * @param merchantId 商家ID
     * @return 统计数据
     */
    @Override
    public ReviewStatisticsVO selectReviewStatistics(Long merchantId) {
        // 查询基础统计数据
        ReviewStatisticsVO statistics = orderReviewMapper.selectReviewStatistics(merchantId);
        
        // 查询评分分布
        List<ReviewStatisticsVO.ScoreDistribution> scoreDistribution = 
            orderReviewMapper.selectScoreDistribution(merchantId);
        
        // 计算每个评分的占比
        if (statistics.getTotalCount() > 0) {
            scoreDistribution.forEach(item -> {
                BigDecimal percentage = BigDecimal.valueOf(item.getCount())
                    .multiply(BigDecimal.valueOf(100))
                    .divide(BigDecimal.valueOf(statistics.getTotalCount()), 2, RoundingMode.HALF_UP);
                item.setPercentage(percentage);
            });
        }
        
        statistics.setScoreDistribution(scoreDistribution);
        
        // 格式化数据
        if (statistics.getAvgScore() != null) {
            statistics.setAvgScore(statistics.getAvgScore().setScale(1, RoundingMode.HALF_UP));
        }
        if (statistics.getGoodRate() != null) {
            statistics.setGoodRate(statistics.getGoodRate().setScale(2, RoundingMode.HALF_UP));
        }
        
        return statistics;
    }
}
